import axios, { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';

// 创建 axios 实例
const service: AxiosInstance = axios.create({
    baseURL:  import.meta.env.VITE_BASE_URL || "http://127.0.0.1:9013",
    timeout: 10000,
    headers: axios.defaults.headers
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const accessToken = sessionStorage.getItem('AccessToken');
        if (accessToken) {
            config.headers['AccessToken'] = accessToken;
        }
        
        config.headers['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdXRocyI6IioiLCJyb2xlcyI6Im1hc3RlciIsIm1vYmlsZSI6IjE1MDAxMjM2OTE4Iiwibmlja25hbWUiOiLnrqHnkIblkZgiLCJ1c2VySWQiOiIxIiwiYWNjb3VudCI6Im1hc3RlciJ9.Nr0kF5Jvh4iQ2OK-R9QIXlpI1n9UNUzgCjddo2JuFQE';
        return config;
    },
    (error: AxiosError) => {
        console.error('Request error:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response.data;
        }
        return Promise.reject(new Error('Server error status: ' + response.status + ' ' + response.statusText));
    },
    (error: AxiosError) => {
        console.error('Response error:', error);
        return Promise.reject(error);
    }
);

export default service;


